﻿using Microsoft.AspNetCore.Http;
using mozhi.smarterp.Finance.Accounts;
using mozhi.smarterp.Finance.Enums;
using Mozhi.Abp.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;

namespace mozhi.smarterp.Finance.Finances.Services.EndPeriodProcess
{
    public class TransferVATEndPeriodProcessor : EndPeriodProcessorBase<AccountBalance>
    {
        public TransferVATEndPeriodProcessor(EndPeriodProcessItem item, int period, IServiceProvider serviceProvider) : base(item, period, serviceProvider)
        {
        }

        /// <summary>
        /// 获取处理结果
        ///1.收入为0，成本也为0，不需要结转
        ///2.如果收入不为0，则默认百分比 =  库存商品余额 / 收入
        ///3.如果上期有用户输入的百分比，则采用上期的，如果根据上百分比计算出来的成本金额大于库存商品余额，则使用第二条规则。
        ///4.结转百分比可以为任何值，如果结转百分比超过100%，点击创建的时候，弹出确认框给用户确认
        /// </summary>
        /// <returns></returns>
        protected override async Task<EndPeriodProcessResult> HandleDataAsync()
        {
            //取综合本位币金额
            _data = _data.Where(x => x.CurrencyId == null && x.DimensionGroupValueId == null).ToList();

            ///应交增值税科目
            var account222101 = GetAccount(GetEndPeriodProcessSettingAsync("222101")?.CustomAccountCode);

            //未交增值税科目
            var account222102 = GetAccount(GetEndPeriodProcessSettingAsync("222102")?.CustomAccountCode);


            //应交增值税科目余额
            var balances22101 = _data.Where(x => x.AccountId == account222101.Id).ToList();

            //测算的金额
            var measureAmount = balances22101.Where(x => x.ClosingAmount.HasValue).Sum(x => x.ClosingAmount.Value);

            var result = new EndPeriodProcessResult(_guidGenerator.Create(), _item.Id, _period, Enums.EndPeriodProcessType.TransferVAT);

            result.Change(measureAmount > 0, false, null, measureAmount.ToDecimal(2), false);

            var resultItems = GetResultItems(result.Id, measureAmount < 0 ? 0 : measureAmount);

            resultItems.ForEach(x =>
            {
                result.AddItem(x);
            });

            return result;
        }


        protected override async Task<Journal> HandleGenerateJournalAsync()
        {
            _data = _data.Where(x => x.DimensionGroupValueId != null && x.CurrencyId != null).ToList();

            ///应交增值税科目
            var account22210103 = GetFirstLeafAccount(GetEndPeriodProcessSettingAsync("22210103")?.CustomAccountCode);


            //未交增值税
            var account222102 = GetFirstLeafAccount(GetEndPeriodProcessSettingAsync("222102")?.CustomAccountCode);

            var measureResult = await GetEndPeriodResultAsync();

            if (measureResult.MeasureValue.Value <= 0)
                throw new UserFriendlyException("本期无需处理", "100000");

            var journalMananger = _serviceProvider.GetService(typeof(JournalManager)) as JournalManager;

            var defaultJournalNumberPrefix = await GetJournalDefaultNumberPrefix();

            var journal = await journalMananger.Create(_guidGenerator.Create(), defaultJournalNumberPrefix.Id, _period.ToLastDayDateTime());

            var journalItem222102 = await GetJournalItemAsync("结转未交增值税", measureResult.MeasureValue.Value, account222102, null, 1, AccountDirectionType.Credit);

            var journalItem22210103 = await GetJournalItemAsync("结转未交增值税", measureResult.MeasureValue.Value, account22210103, null, 0, AccountDirectionType.Debit);

            var journalItems = new List<JournalItem>() { journalItem222102, journalItem22210103 };

            await journalMananger.ChangeItems(journal, journalItems);

            return journal;
        }

        #region
        private List<EndPeriodProcessResultItem> GetResultItems(Guid resultId , decimal measureAmount)
        {
            var result = new List<EndPeriodProcessResultItem>();

            //设置子处理项
            result.Add(new EndPeriodProcessResultItem(_guidGenerator.Create(), resultId, "本期应交增值税", measureAmount.ToString(), 1, 1, false));

            return result;
        }
        #endregion
    }
}
